package com.shuaiche.yeguan.ui.login;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.geetest.sdk.GT3ConfigBean;
import com.geetest.sdk.GT3ErrorBean;
import com.geetest.sdk.GT3GeetestUtils;
import com.geetest.sdk.GT3Listener;
import com.geetest.sdk.utils.GT3ServiceNode;
import com.google.gson.Gson;
import com.shuaiche.yeguan.MainActivity;
import com.shuaiche.yeguan.R;
import com.shuaiche.yeguan.SCApplication;
import com.shuaiche.yeguan.config.HttpUrl;
import com.shuaiche.yeguan.config.SCAppConfig;
import com.shuaiche.yeguan.config.SCUserInfoConfig;
import com.shuaiche.yeguan.model.BaseResponseModel;
import com.shuaiche.yeguan.model.SCUserInfoResponse;
import com.shuaiche.yeguan.net.http.HttpCallBack;
import com.shuaiche.yeguan.net.http.HttpHelper;
import com.shuaiche.yeguan.ui.common.WebviewActivity;
import com.shuaiche.yeguan.util.DeviceHelper;
import com.shuaiche.yeguan.util.SCAddSpaceTextWatcher;
import com.shuaiche.yeguan.util.SCCodeCountDownUtils;
import com.shuaiche.yeguan.util.SPUtils;
import com.shuaiche.yeguan.util.StringUtils;
import com.shuaiche.yeguan.util.ToastShowUtils;
import com.shuaiche.yeguan.views.SCClearEditText;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "LoginActivity";
    private static final String GEETEST_VALIDATE = "geetest_validate";
    private static final String GEETEST_SECCODE = "geetest_seccode";
    private static final String GEETEST_CHALLENGE = "geetest_challenge";
    private SCClearEditText et_phone;
    private SCClearEditText et_code;
    private Button btn_login;
    private Button btn_get_code;
    private CheckBox cb_login;
    private TextView toolbar_title;
    private TextView tv_service;
    private TextView tv_privacy;
    private Toolbar toolbar;
    private GT3GeetestUtils gt3GeetestUtils;
    private GT3ConfigBean gt3ConfigBean;

    private String phone;
    private SCCodeCountDownUtils codeCountDownUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        setContentView(R.layout.activity_login);

        initViews();
    }

    private void initViews() {
        et_phone = findViewById(R.id.et_phone);
        et_code = findViewById(R.id.et_code);
        btn_login = findViewById(R.id.btn_login);
        btn_get_code = findViewById(R.id.btn_get_code);
        cb_login = findViewById(R.id.cb_login);
        toolbar_title = findViewById(R.id.toolbar_title);
        toolbar = findViewById(R.id.toolbar);
        tv_privacy = findViewById(R.id.tv_privacy);
        tv_service = findViewById(R.id.tv_service);
        btn_login.setOnClickListener(this);
        btn_get_code.setOnClickListener(this);
        tv_service.setOnClickListener(this);
        tv_privacy.setOnClickListener(this);



        SCAddSpaceTextWatcher asTextWatcher = new SCAddSpaceTextWatcher(et_phone, 13);
        asTextWatcher.setSpaceType(SCAddSpaceTextWatcher.SpaceType.mobilePhoneNumberType);

        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null){
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }

        String phone = SPUtils.getString(this,SPUtils.LAST_PHONE,"");
        if (!TextUtils.isEmpty(phone)){
            et_phone.setText(phone);
        }

        geetestInit();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 初始化极验
     */
    private void geetestInit() {
        gt3GeetestUtils = new GT3GeetestUtils(this);

        gt3ConfigBean = new GT3ConfigBean();
        gt3ConfigBean.setPattern(1);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        gt3ConfigBean.setUnCanceledOnTouchKeyCodeBack(preferences.getBoolean("settings_switch_key_back", true));
        gt3ConfigBean.setCanceledOnTouchOutside(preferences.getBoolean("settings_switch_background", true));
        gt3ConfigBean.setLang(preferences.getString("settings_language", null));
        gt3ConfigBean.setTimeout(Integer.parseInt(preferences.getString("settings_timeout_load_web", "100000")));
        // 设置 WebView 内部 H5 页面请求超时, 单位 ms, 默认 10000
        gt3ConfigBean.setWebviewTimeout(Integer.parseInt(preferences.getString("settings_timeout_h5", "100000")));
        // 设置验证服务集群节点, 默认为中国节点, 使用其他节点需要相应配置, 否则无法使用验证
        gt3ConfigBean.setGt3ServiceNode(GT3ServiceNode.NODE_CHINA);

        //设置自定义LoadingView
//        GT3LoadImageView gt3LoadImageView = new GT3LoadImageView(SCLoginFragment.this.getActivity());
//        gt3LoadImageView.setIconRes(R.drawable.loading_test);
//        gt3LoadImageView.setLoadViewHeight(48);
//        gt3LoadImageView.setLoadViewWidth(48);
//        gt3ConfigBean.setLoadImageView(gt3LoadImageView);
        gt3ConfigBean.setListener(new GT3Listener() {

            /**
             * 验证码加载完成
             * @param duration 加载时间和版本等信息，为json格式
             */
            @Override
            public void onDialogReady(String duration) {
                Log.e(TAG, "GT3BaseListener-->onDialogReady-->" + duration);
            }

            /**
             * 图形验证结果回调
             * @param code 1为正常 0为失败
             */
            @Override
            public void onReceiveCaptchaCode(int code) {
                Log.e(TAG, "GT3BaseListener-->onReceiveCaptchaCode-->" + code);
            }

            /**
             * 自定义api2回调
             * @param result，api2请求上传参数
             */
            @Override
            public void onDialogResult(String result) {
                Log.e(TAG, "GT3BaseListener-->onDialogResult-->" + result);
                // 开启自定义api2逻辑
//                new RequestAPI2().execute(result);
                // todo 上传参数
                String seccode = "", validate = "", challenge = "";
                Map<String, String> map = new HashMap<>();
                map.put("phone", phone);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    seccode = jsonObject.getString(GEETEST_SECCODE);
                    validate = jsonObject.getString(GEETEST_VALIDATE);
                    challenge = jsonObject.getString(GEETEST_CHALLENGE);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                /**
                 * {"business_param":{"phone":"19884184578"},
                 * "business_type":"login",
                 * "geetest_challenge":"c5d65701dc1a8e91bffce50850a72ecej0",
                 * "geetest_seccode":"eb390afba498578eda2914403ce8933f|jordan",
                 * "geetest_validate":"eb390afba498578eda2914403ce8933f"}
                 */
                JSONObject paramJson = new JSONObject();
                try {
                    paramJson.put("geetest_challenge",challenge);
                    paramJson.put("geetest_validate",validate);
                    paramJson.put("geetest_seccode",seccode);
                    paramJson.put("business_type","login");
                    paramJson.put("business_param",new JSONObject(map));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                HttpHelper.getInstance().appendUrl(HttpUrl.GEETEST_VALIDATE).
                        addJsonParam(paramJson.toString())
                        .jsonPost(new HttpCallBack<BaseResponseModel>(LoginActivity.this) {

                            @Override
                            public void onSuccessed(BaseResponseModel result) {
                                Gson gson = new Gson();
                                String json = gson.toJson(result.getData());
                                JSONObject jsonObject = null;
                                try {
                                    jsonObject = new JSONObject(json);
                                    String status = jsonObject.optString("result");
                                    if (TextUtils.isEmpty(status)) {
                                        status = jsonObject.optString("status");
                                    }
                                    if ("success".equals(status)) {
                                        gt3GeetestUtils.showSuccessDialog();
                                        // tip : 极验验证通过后 服务端发送验证码
                                        new Handler().postDelayed(() -> {
                                            codeCountDownUtils = new SCCodeCountDownUtils(LoginActivity.this, 60000, 1000, btn_get_code);
                                            codeCountDownUtils.start();
                                            SCCodeCountDownUtils.isGetSmsCode = true;
                                        }, 1000);
                                    } else {
                                        gt3GeetestUtils.showFailedDialog();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    gt3GeetestUtils.showFailedDialog();
                                }
                            }

                            @Override
                            public void onFailured(String errorCode, String errMsg) {
                                ToastShowUtils.showFailedToast(errMsg);

                            }


                        });


            }

            /**
             * 统计信息，参考接入文档
             * @param result
             */
            @Override
            public void onStatistics(String result) {
                Log.e(TAG, "GT3BaseListener-->onStatistics-->" + result);
            }

            /**
             * 验证码被关闭
             * @param num 1 点击验证码的关闭按钮来关闭验证码, 2 点击屏幕关闭验证码, 3 点击返回键关闭验证码
             */
            @Override
            public void onClosed(int num) {
                Log.e(TAG, "GT3BaseListener-->onClosed-->" + num);
            }

            /**
             * 验证成功回调
             * @param result
             */
            @Override
            public void onSuccess(String result) {
                Log.e(TAG, "GT3BaseListener-->onSuccess-->" + result);
            }


            /**
             * 验证失败回调
             * @param errorBean 版本号，错误码，错误描述等信息
             */
            @Override
            public void onFailed(GT3ErrorBean errorBean) {
                Log.e(TAG, "GT3BaseListener-->onFailed-->" + errorBean.toString());
            }

            /**
             * 自定义api1回调
             */
            @Override
            public void onButtonClick() {

            }
        });
        gt3GeetestUtils.init(gt3ConfigBean);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_login){
            if (!verificationPhone()) {
                ToastShowUtils.showTipToast("手机号码格式有误");
                return;
            }
            if (TextUtils.isEmpty(et_code.getText())) {
                ToastShowUtils.showTipToast("请输入验证码");
                return;
            }
            if (!cb_login.isChecked()) {
                ToastShowUtils.showTipToast("请选择同意用户协议");
                return;
            }

            login();
        }else if (v.getId() == R.id.btn_get_code){
            if (verificationPhone()){
                Map<String,Object> maps = new HashMap<>();
                maps.put("client_type","native");
                maps.put("t",System.currentTimeMillis());
                HttpHelper.getInstance().appendUrl(HttpUrl.GEETEST_REGISTER)
                        .addGetParam(maps)
                        .get(new HttpCallBack<BaseResponseModel>(LoginActivity.this) {

                            @Override
                            public void onSuccessed(BaseResponseModel data) {
                                if (data != null && data.getData() != null) {
                                    String json = data.getData().toString();
                                    // {"success":1,"challenge":"06fbb267def3c3c9530d62aa2d56d018","gt":"019924a82c70bb123aae90d483087f94","new_captcha":true}
                                    JSONObject jsonObject = null;
                                    int success = 0;
                                    try {
                                        jsonObject = new JSONObject(json);
                                        success = jsonObject.optInt("success");

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    gt3ConfigBean.setApi1Json(jsonObject);
                                    if (success == 1) {
//                                    gt3ConfigBean.setApi1Json(jsonObject);
                                        gt3GeetestUtils.startCustomFlow();
                                        gt3GeetestUtils.getGeetest();
                                    } else {
//                                    SCApiManager.instance().getPicCode(SCLoginFragment.this, phone, SCLoginFragment.this);

                                    }
                                }
                            }

                            @Override
                            public void onFailured(String errorCode, String errMsg) {
                                ToastShowUtils.showFailedToast(errMsg);

                            }


                        });

            }else {
                ToastShowUtils.showTipToast("手机号码格式有误");
            }
        }else if (v.getId() == R.id.tv_privacy){
            Intent bundle = new Intent(this, WebviewActivity.class);
            bundle.putExtra("url", SCAppConfig.URL_PROTOCOL_PRIVACY);
            bundle.putExtra("bundleTitle", "隐私协议");
            startActivity(bundle);
        } else if (v.getId() == R.id.tv_service) {
            Intent bundle = new Intent(this, WebviewActivity.class);
            bundle.putExtra("url", SCAppConfig.URL_PROTOCOL_SERVICE);
            bundle.putExtra("bundleTitle", "用户协议");
            startActivity(bundle);
        }
    }

    /**
     * 验证手机
     */
    private boolean verificationPhone() {
        phone = et_phone.getText().toString().trim().replace(" ", "");
        return StringUtils.isPhoneNumbValid(phone);
    }

    private void login(){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("source", 14);
            jsonObject.put("version", DeviceHelper.getAppVersion());
            jsonObject.put("loginType", 1);

            jsonObject.put("geetest", null);
            jsonObject.put("authorCode", et_code.getText());
            jsonObject.put("phone", phone);
            jsonObject.put("ip", DeviceHelper.getNetworkIP());
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        SPUtils.saveInt(this,SPUtils.API_TYPE,1);
        HttpHelper.getInstance().appendUrl(HttpUrl.URL_LOGIN).
                addJsonParam(jsonObject.toString())
                .jsonPost(new HttpCallBack<SCUserInfoResponse>(this) {

                    @Override
                    public void onSuccessed(SCUserInfoResponse result) {

                        updateUserInfo(result);
                    }

                    @Override
                    public void onFailured(String errorCode, String errMsg) {
                        ToastShowUtils.showFailedToast(errMsg);
                    }
                });
    }


    private void updateUserInfo(BaseResponseModel data) {
        SCUserInfoResponse userInfoResponse = (SCUserInfoResponse) data.getData();

        if (userInfoResponse == null){
            Log.e("updateUserInfo","userInfoResponse == null");
            return;
        }
        SCUserInfoConfig.saveUserinfo(userInfoResponse);  //保存用户信息
        Log.e("updateUserInfo",userInfoResponse.getUsername());
        SPUtils.saveString(this,SPUtils.LAST_PHONE,userInfoResponse.getUsername());
//        SCApplication.getApplication().getPreferenceConfig().setString("account", userInfoResponse.getUsername());
//
//        SCApplication.getApplication().getPreferenceConfig().setString("imUserId", userInfoResponse.getImUserId());
//        SCApplication.getApplication().getPreferenceConfig().setString("imToken", userInfoResponse.getImToken());
//        SCApplication.getApplication().getPreferenceConfig().setString("imTokenExpireTimeSeconds", userInfoResponse.getImTokenExpireTimeSeconds()+"");

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
//        SCApplication.getApplication().getPreferenceConfig().setString("messageTime", date);
        SCUserInfoConfig.deleteMessageInfo();

//        try {
//            ReactContext reactContext =  SCApplication.getApplication().getReactNativeHost().getReactInstanceManager().getCurrentReactContext();
//            if (reactContext == null) {
//                return;
//            }
//            WritableMap event = Arguments.createMap();
//            //传递的参数
//            event.putString("appmobile", userInfoResponse.getUsername());
//            event.putString("merchantId", userInfoResponse.getMerchantId()+"");
//            event.putString("userId", userInfoResponse.getUserId()+"");
//            event.putString("sessionId", userInfoResponse.getSessionId()+"");
//            event.putString("merchantName", userInfoResponse.getMerchantName()+"");
//            event.putString("fullName", userInfoResponse.getFullname()+"");
//            reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("loginSuccess", event);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        //登录成功回调

        Intent intent =  new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }


}